package edu.ucla.cs.cs144;

import java.lang.Integer;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

public class SearchServlet extends HttpServlet implements Servlet {
       
    public SearchServlet() {}

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
		HttpSession session = request.getSession(true);		// Don't know what to do with this yet
		
		request.getParameter("q");
		
		String q = request.getParameter("q");
		int numResultsToSkip = Integer.parseInt(request.getParameter("numResultsToSkip"));
		int numResultsToReturn = Integer.parseInt(request.getParameter("numResultsToReturn"));
		
		SearchResult[] result = AuctionSearchClient.basicSearch(q, numResultsToSkip, numResultsToReturn);
		
		JSONObject json = new JSONObject();
		
		for (int i = 0; i < result.length; i++)
			json.put(encode(result[i].getItemId()), encode(result[i].getName()));
		
		request.setAttribute("returned", result.length);
		request.setAttribute("result", json.toString());
		request.getRequestDispatcher("/searchResult.jsp").forward(request, response);		
    }
	
	// Encodes a string with escape characters
	private String encode(String s) {
		
		return s.replaceAll("\"", "&quot;")
				.replaceAll("\'", "&apos;")
				.replaceAll("&", "&amp;")
				.replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
